#pragma once

#include <iostream>
#include <memory>
#include <fstream>
#include <sstream>
#include <ctime>
#include "Mutex.hpp"
#include <filesystem>
#include <unistd.h>

namespace LogModule
{
    using namespace MutexModule;
    const std::string sep = "\r\n";

    // 策略模式基类
    class LogStrategy
    {
    public:
        virtual ~LogStrategy() = default;

        virtual void SyncLog(const std::string &message) = 0;
    };

    // 向显示器输出日志文件的策略子类
    class ConsoleLogStrategy : public LogStrategy
    {
    public:
        ~ConsoleLogStrategy()
        {
        }

        void SyncLog(const std::string &message) override
        {
            MutexGuard guard(_mutex);

            std::cout << message << sep;
        }

    private:
        Mutex _mutex;
    };

    const std::string defaultpath = "./log";
    const std::string defaultname = "my.log";

    // 向文件输出日志文件的策略子类
    class FileLogStrategy : public LogStrategy
    {
    public:
        FileLogStrategy(const std::string &path = defaultpath, const std::string &name = defaultname)
            : _path(path), _name(name)
        {
            MutexGuard guard(_mutex);

            if (std::filesystem::exists(_path))
            {
                return;
            }

            try
            {
                std::filesystem::create_directories(_path);
            }
            catch (const std::filesystem::filesystem_error &e)
            {
                std::cerr << e.what() << '\n';
            }
        }

        void SyncLog(const std::string &message) override
        {
            MutexGuard guard(_mutex);

            std::string filename = _path + (_path.back() == '/' ? "" : "/") + _name;
            std::ofstream ofs(filename, std::ios::app);
            if (!ofs.is_open())
            {
                return;
            }

            ofs << message << sep;

            ofs.close();
        }

        ~FileLogStrategy()
        {
        }

    private:
        Mutex _mutex;
        std::string _path;
        std::string _name;
    };

    // 形成一个完整的日志，根据上面的策略，选择不同的刷新方式

    enum class LogLevel
    {
        Debug,
        Info,
        Warning,
        Error,
        Fatal
    };

    std::string GetTimeStamp()
    {

        time_t curr = time(nullptr);
        struct tm curr_tm;
        localtime_r(&curr, &curr_tm);

        char time_buff[128];
        snprintf(time_buff, sizeof(time_buff), "%4d-%02d-%02d %02d:%02d:%02d",
                 curr_tm.tm_year + 1900,
                 curr_tm.tm_mon + 1,
                 curr_tm.tm_mday,
                 curr_tm.tm_hour,
                 curr_tm.tm_min,
                 curr_tm.tm_sec);

        return time_buff;
    }

    std::string LogLevelToString(LogLevel level)
    {
        switch (level)
        {
        case LogLevel::Debug:
            return "Debug";
        case LogLevel::Info:
            return "Info";
        case LogLevel::Warning:
            return "Warning";
        case LogLevel::Error:
            return "Error";
        case LogLevel::Fatal:
            return "Fatal";
        default:
            return "Unknown";
        }
    }

    class Logger
    {
    public:
        void EnableConsoleLogStrategy()
        {
            _fflush_strategy = std::make_unique<ConsoleLogStrategy>();
        }

        void EnableFileLogStrategy()
        {
            _fflush_strategy = std::make_unique<FileLogStrategy>();
        }

        Logger()
        {
            EnableConsoleLogStrategy();
        }

        // 表示未来的一条日志
        class LogMessage
        {
        public:
            LogMessage(LogLevel &level, std::string &src_name, int line_number, Logger &logger)
                : _curr_time(GetTimeStamp()), _level(level), _pid(getpid()), _src_name(src_name), _line_number(line_number), _logger(logger)
            {
                std::stringstream ss;
                ss << "[" << _curr_time << "]"
                   << "[" << LogLevelToString(_level) << "]"
                   << "[" << _pid << "]"
                   << "[" << _src_name << "]"
                   << "[" << _line_number << "]"
                   << "-";

                _loginfo = ss.str();
            }

            template <class T>
            LogMessage &operator<<(const T &info)
            {
                std::stringstream ss;
                ss << info;
                _loginfo += ss.str();

                return *this;
            }

            ~LogMessage()
            {
                if (_logger._fflush_strategy)
                {
                    _logger._fflush_strategy->SyncLog(_loginfo);
                }
            }

        private:
            std::string _curr_time;
            LogLevel _level;
            pid_t _pid;
            std::string _src_name;
            int _line_number;
            std::string _loginfo; // 合并之后，一条完整的日志信息
            Logger &_logger;      // 内部类可以直接引用外部类对象，传logger进来是为了在LogMessage对象析构时，能调用策略方法，将日志刷新出去
        };

        // 这里故意写成返回临时对象，这样在临时对象获取完loginfo时，自动析构时就把日志文件刷新出来了
        LogMessage operator()(LogLevel level, std::string name, int line_number)
        {
            return LogMessage(level, name, line_number, *this);
        }

        ~Logger()
        {
        }

    private:
        std::unique_ptr<LogStrategy> _fflush_strategy;
    };

    Logger logger;

#define LOG(level) logger(level, __FILE__, __LINE__)
#define Enable_Console_Log_Strategy() logger.EnableConsoleLogStrategy()
#define Enable_File_Log_Strategy() logger.EnableFileLogStrategy()

}